package com.example.sherlockzhong.plush_v2.Models;

import com.example.sherlockzhong.plush_v2.Utils.StorageUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Created by SherlockZhong on 10/2/14.
 */
public class TodoModel {

    public static boolean add (JSONObject todoItem) {
        JSONArray todoList = retrieveTodoList();
        if (todoList == null) {
            todoList = new JSONArray();
        }
        todoList.put(todoItem);
        return StorageUtils.saveAsFile("TodoList.json", todoList.toString());
    }

    public static boolean remove (int index) {
        JSONArray oldList = retrieveTodoList();
        JSONArray newList = new JSONArray();
        try {
            if (oldList != null && oldList.length() > 0) {
                for (int i = 0; i < oldList.length(); i++) {
                    if (i != index) {
                        newList.put(oldList.get(i));
                    }
                }
                return StorageUtils.saveAsFile("TodoList.json", newList.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static JSONArray retrieveTodoList() {
        try {
            if (StorageUtils.fileExists("/data/TodoList.json")) {
                String raw = StorageUtils.retrieveFromFile("TodoList.json");
                JSONTokener jsonTokener = new JSONTokener(raw);
                return (JSONArray) jsonTokener.nextValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
